package cn.demoncat.util.websocket.listener;

import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;

import cn.demoncat.util.web.entity.TokenPrincipal;
import cn.demoncat.util.websocket.util.WebSocketStompUtil;

/**
 * WebSocketStomp客户端订阅事件监听
 * 
 * @author 延晓磊
 *
 * @since 2020年3月4日
 */
@Component
public class WebSocketStompSubscribeListener implements ApplicationListener<SessionSubscribeEvent> {

	@Override
	public void onApplicationEvent(SessionSubscribeEvent event) {
		// 获取STOMP协议请求头
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(event.getMessage(), StompHeaderAccessor.class);
        // 获取订阅主题：/topic/xx 或 /user/quque/xx
        String queue = accessor.getDestination();
        // 是否为用户主题
        if (WebSocketStompUtil.isUserPath(queue)) {
        	// 获取连接用户
    		TokenPrincipal user = (TokenPrincipal)event.getUser();
    		// 添加订阅
    		WebSocketStompUtil.addQueue(user, queue);
		}
	}

}
